import { ActorSystem } from '../actor/actorSystem';
import { Props } from '../actor/props';
import { PID } from '../actor/pid';
import { Serializer } from './serializer';
import { EndpointManager } from './endpointManager';
import { RemoteActivator, RemoteActivationRequest, RemoteActivationResponse } from './remoteActivator';
import { RemoteProcess } from './remoteProcess';
import { Events } from '../actor/eventStream';
import { Process } from '../actor/process';
import { ProcessRegistry } from '../actor/processRegistry';
import { 
  RemoteTerminate,
  RemoteWatch,
  RemoteUnwatch,
  RemoteDeliver,
  RemoteFuture
} from './remoteMessages';
import { EventEmitter } from 'events';
import { Future } from '../actor/future';
import { Libp2pProvider } from '../cluster/providers/libp2pProvider';

/**
 * 远程通信协议类型
 */
export enum RemoteProtocolType {
  WebSocket = 'websocket',
  Libp2p = 'libp2p'
}

/**
 * 远程消息类型
 */
export enum RemoteMessageType {
  Normal = 'Normal',
  System = 'System',
  Request = 'Request',
  Response = 'Response',
  Activation = 'Activation',
  ActivationResponse = 'ActivationResponse',
  ErrorResponse = 'ErrorResponse'
}

export interface RemoteMessage {
  type: RemoteMessageType;
  targetPID?: PID;
  senderPID?: PID;
  message: unknown;
  messageId?: string;
}

export interface RemoteErrorResponse {
  type: RemoteMessageType.ErrorResponse;
  error: string;
  messageId: string;
}

/**
 * 远程配置
 */
export class RemoteConfig {
  hostname: string = '';
  port: number = 0;
  serializer?: Serializer;
  advertisedHostname?: string;
  advertisedPort?: number;
  // 添加协议类型支持
  protocolType: RemoteProtocolType = RemoteProtocolType.WebSocket;
  // libp2p 提供者 (当协议类型为 libp2p 时使用)
  libp2pProvider?: Libp2pProvider;
}

export class Remote {
  private system: ActorSystem;
  private config: RemoteConfig;
  private endpointManager: EndpointManager;
  private activator: RemoteActivator;
  private started: boolean = false;
  private kindMap: Map<string, Props> = new Map();

  constructor(system: ActorSystem) {
    this.system = system;
    this.config = new RemoteConfig();
    this.endpointManager = new EndpointManager(system);
    this.activator = new RemoteActivator(system);
  }

  /**
   * 启动远程系统
   * @param hostname 主机名
   * @param port 端口
   */
  async start(hostname: string, port: number): Promise<void> {
    if (this.started) {
      console.warn('[REMOTE] Remote system already started');
      return;
    }

    console.log(`[REMOTE] Starting remote system at ${hostname}:${port} using ${this.config.protocolType} protocol`);
    
    // 存储配置
    this.config.hostname = hostname;
    this.config.port = port;

    // 设置协议类型到ProcessRegistry
    if (this.config.protocolType === RemoteProtocolType.Libp2p && this.config.libp2pProvider) {
      // 如果使用libp2p协议，从provider获取peerId
      const peerId = this.config.libp2pProvider.getPeerId();
      
      console.log(`[REMOTE] Setting libp2p protocol type with peerId: ${peerId}`);
      ProcessRegistry.setProtocolType('libp2p', peerId);
    } else {
      // 使用普通协议类型
      console.log(`[REMOTE] Setting protocol type: ${this.config.protocolType}`);
      ProcessRegistry.setProtocolType(this.config.protocolType);
    }
    
    // 确保 EndpointManager 有正确的配置
    this.endpointManager.setConfig(this.config);
    
    // 创建远程服务器进程
    const remoteId = 'remote$0';
    const serverPid = new PID(`${hostname}:${port}`, remoteId);
    
    console.log(`[REMOTE] Registering server process at ${serverPid.toString()}`);
    const serverProcess = this.createServerProcess(remoteId);
    
    // 将远程进程添加到系统进程注册表
    const registeredPid = this.system.processRegistry.add(serverProcess, remoteId);
    registeredPid.system = this.system;
    console.log(`[REMOTE] Server process registered with PID: ${registeredPid.toString()}`);
    
    try {
      // 启动网络服务
    await this.endpointManager.start();
      console.log(`[REMOTE] ${this.config.protocolType} server listening on ${hostname}:${port}`);
      
      // 标记为已启动
    this.started = true;
      
      // 将自身注册到 ActorSystem
      if (typeof (this.system as any).setRemote === 'function') {
        (this.system as any).setRemote(this);
        console.log(`[REMOTE] Remote system registered with ActorSystem`);
      }
      
      console.log(`[REMOTE] Remote system started on ${hostname}:${port}`);
    } catch (error) {
      console.error(`[REMOTE] Failed to start remote system:`, error);
      throw error;
    }
  }

  /**
   * 发送远程消息
   * @param targetPID 目标PID
   * @param message 消息内容
   */
  async sendRemoteMessage(targetPID: PID, message: any): Promise<void> {
    if (!this.started) {
      throw new Error('Remote not started');
    }
    
    console.log(`[REMOTE] 发送远程消息到 ${targetPID.toString()}`);
    
    try {
      // 准备消息
      const remoteMessage: RemoteMessage = {
        type: RemoteMessageType.Normal,
        targetPID,
        message
      };
      
      // 如果消息是信封格式，添加发送者信息
      if (message && typeof message === 'object' && message.sender) {
        remoteMessage.senderPID = message.sender;
        console.log(`[REMOTE] 消息包含发送者: ${message.sender.toString()}`);
      }
      
      // 准备消息序列化
      const prepareMessageForSerialization = (msg: any): any => {
        // 如果消息是 PID 类型，转换为可序列化格式
        if (msg instanceof PID) {
          return {
            address: msg.address,
            id: msg.id,
            __pid: true
          };
        }
        
        // 如果消息是对象，递归处理其属性
        if (msg && typeof msg === 'object' && !Array.isArray(msg)) {
          const result: any = {};
          for (const key in msg) {
            if (Object.prototype.hasOwnProperty.call(msg, key)) {
              result[key] = prepareMessageForSerialization(msg[key]);
            }
          }
          return result;
        }
        
        // 如果消息是数组，递归处理其元素
        if (Array.isArray(msg)) {
          return msg.map(item => prepareMessageForSerialization(item));
        }
        
        // 其他类型直接返回
        return msg;
      };
      
      // 序列化消息
      const serializedMessage = prepareMessageForSerialization(remoteMessage);
      
      // 根据协议类型选择不同的发送方式
      if (this.config.protocolType === RemoteProtocolType.Libp2p) {
        // 使用 libp2p 发送消息
        if (!this.config.libp2pProvider) {
          throw new Error('Libp2p provider not configured');
        }
        
        console.log(`[REMOTE] 通过 libp2p 发送消息到 ${targetPID.address}`);
        await this.config.libp2pProvider.sendMessage(targetPID.address, serializedMessage);
        console.log(`[REMOTE] 消息已通过 libp2p 发送`);
      } 
      else {
        // 使用 WebSocket 发送消息
        console.log(`[REMOTE] 通过 WebSocket 发送消息到 ${targetPID.address}`);
        
        // 定义重试逻辑
        const sendWithRetry = async () => {
          try {
            await this.endpointManager.sendMessage(targetPID.address, serializedMessage);
            console.log(`[REMOTE] 消息已通过 WebSocket 发送`);
          } catch (error) {
            console.error(`[REMOTE] 发送消息失败:`, error);
            throw error;
          }
        };
        
        // 执行发送
        await sendWithRetry();
      }
    } catch (error) {
      console.error(`[REMOTE] 发送远程消息失败:`, error);
      throw error;
    }
  }

  // 关闭远程处理
  async shutdown(): Promise<void> {
    if (!this.started) {
      return;
    }

    await this.endpointManager.shutdown();
    this.started = false;
  }

  // 注册可远程激活的 Actor
  register(kind: string, props: Props): void {
    this.kindMap.set(kind, props);
  }

  // 获取远程 PID
  activatorForAddress(address: string): PID {
    if (!this.started) {
      throw new Error('Remote not started');
    }
    
    console.log(`[REMOTE] Creating remote process for address: ${address}`);
    
    // 定义远程进程 ID 格式
    const remoteId = 'remote$0';
    
    // 创建 PID 对象
    const pid = new PID(address, remoteId);
    console.log(`[REMOTE] Created PID object: ${pid.address}/${pid.id}`);
    
    // 获取进程注册表实例
    const processRegistry = ProcessRegistry.getInstance();
    
    // 检查是否已存在
    const existingProcess = processRegistry.get(pid);
    if (existingProcess) {
      console.log(`[REMOTE] Reusing existing remote process for address: ${address}`);
      return pid;
    }
    
    // 创建远程进程
    const remoteProcess = new RemoteProcess(pid, this.endpointManager);
    
    // 使用完整 ID 格式注册
    const registeredPid = processRegistry.add(remoteProcess, remoteId);
    registeredPid.system = this.system;
    
    console.log(`[REMOTE] Created and registered remote process with PID: ${registeredPid.address}/${registeredPid.id}`);
    
    return registeredPid;
  }

  // 配置序列化器
  withSerializer(serializer: Serializer): Remote {
    this.config.serializer = serializer;
    return this;
  }

  // 配置协议类型
  withProtocol(protocolType: RemoteProtocolType): Remote {
    this.config.protocolType = protocolType;
    return this;
  }

  // 配置 libp2p 提供者
  withLibp2pProvider(provider: Libp2pProvider): Remote {
    if (this.config.protocolType !== RemoteProtocolType.Libp2p) {
      this.config.protocolType = RemoteProtocolType.Libp2p;
    }
    this.config.libp2pProvider = provider;
    return this;
  }

  // 获取当前状态
  isStarted(): boolean {
    return this.started;
  }

  // 处理远程消息
  private async handleRemoteMessage(message: RemoteMessage): Promise<void> {
    try {
      console.log(`[REMOTE] Handling remote message of type: ${message.type}`);
      console.log(`[REMOTE] Message details:`, JSON.stringify({
        type: message.type,
        targetPID: message.targetPID ? `${message.targetPID.address}/${message.targetPID.id}` : 'none',
        senderPID: message.senderPID ? `${message.senderPID.address}/${message.senderPID.id}` : 'none',
        messageType: typeof message.message
      }));
      
      // 恢复 PID 对象
      if (message.targetPID && typeof message.targetPID === 'object') {
        const target = message.targetPID as any;
        if (!('toString' in target)) {
          console.log(`[REMOTE] Restoring targetPID object: ${JSON.stringify(target)}`);
          message.targetPID = new PID(target.address, target.id);
          message.targetPID.system = this.system;
        }
      }
      
      if (message.senderPID && typeof message.senderPID === 'object') {
        const sender = message.senderPID as any;
        if (!('toString' in sender)) {
          console.log(`[REMOTE] Restoring senderPID object: ${JSON.stringify(sender)}`);
          message.senderPID = new PID(sender.address, sender.id);
          message.senderPID.system = this.system;
        }
      }
      
      // 检查是否是响应消息
      if (message.type === RemoteMessageType.Response) {
        console.log(`[REMOTE] 处理响应消息: 目标PID=${message.targetPID?.toString()}`);
        await this.handleResponseMessage(message);
        return;
      }
      
      // 检查是否是响应消息 (正常消息但目标是 future 进程)
      if (message.type === RemoteMessageType.Normal && 
          message.targetPID && 
          message.targetPID.address === 'local' && 
          message.targetPID.id.startsWith('future$')) {
        console.log(`[REMOTE] Detected response message to future: ${message.targetPID.toString()}`);
        await this.handleResponseToFuture(message);
        return;
      }
      
      // 直接处理消息，不经过serverPid中转
      if (message.targetPID) {
        console.log(`[REMOTE] Directly routing message to target: ${message.targetPID.toString()}`);
        await this.handleNormalMessage(message);
        return;
      }
      
      // 尝试多种方式查找服务器进程
      const remoteId = 'remote$0';
      
      // 尝试使用完整地址查找
      let serverProcess = null;
      const serverAddresses = [
        this.system.processRegistry.address(),  // local
        this.config.hostname + ':' + this.config.port  // 完整地址
      ];
      
      for (const address of serverAddresses) {
        const serverPid = new PID(address, remoteId);
        console.log(`[REMOTE] Looking up server process: ${serverPid.toString()}`);
        
        serverProcess = this.system.processRegistry.get(serverPid);
        if (serverProcess) {
          console.log(`[REMOTE] Found server process at ${serverPid.toString()}, forwarding message`);
          serverProcess.sendUserMessage(serverPid, message);
          return;
        }
      }
      
      // 所有尝试都失败
      console.error(`[REMOTE] Server process not found in any known format`);
      
      // 打印进程注册表状态
      console.log(`[REMOTE] Dumping process registry state:`);
      const registry = this.system.processRegistry as any;
      if (registry._processes) {
        registry._processes.forEach((_: any, key: string) => console.log(`  - ${key}`));
      }
      
      // 尝试直接处理消息
      console.log(`[REMOTE] Trying direct message handling`);
      await this.handleNormalMessage(message);
    } catch (error) {
      console.error(`[REMOTE] Error handling remote message:`, error);
    }
  }

  // 处理激活请求
  private async handleActivationRequest(request: RemoteActivationRequest): Promise<void> {
    try {
      const { kind, actorId } = request;
      
    const response: RemoteActivationResponse = {
        type: RemoteMessageType.ActivationResponse,
        pid: undefined,
        error: undefined,
        messageId: request.messageId
      };
      
      try {
        const actor = await this.activator.activate(kind, actorId);
        if (actor) {
          response.pid = actor;
        } else {
          response.error = `No Props found for kind ${kind}`;
        }
      } catch (err: any) {
        response.error = err?.message || 'Unknown error during activation';
      }
      
      if (request.senderPID) {
        // 发送响应
        const targetAddress = request.senderPID.address;
        await this.endpointManager.sendMessage(targetAddress, response);
      }
    } catch (error) {
      console.error('Error handling activation request:', error);
    }
  }

  // 处理普通消息
  private async handleNormalMessage(message: RemoteMessage): Promise<void> {
    try {
      if (!message.targetPID) {
        console.warn('[REMOTE] Received message without target PID');
        return;
      }

      console.log(`[REMOTE] Processing normal message for target: ${message.targetPID.toString()}`);
      console.log(`[REMOTE] Message details:`, {
        type: message.type,
        messageId: message.messageId,
        hasSender: !!message.senderPID,
        senderPID: message.senderPID?.toString()
      });
      
      // 确保 targetPID 是 PID 实例
      let targetPID: PID;
      if (message.targetPID instanceof PID) {
        targetPID = message.targetPID;
      } else if (typeof message.targetPID === 'object') {
        // 将简单对象转换为PID实例
        const pidObj = message.targetPID as any;
        console.log(`[REMOTE] Converting target PID object to PID instance: ${pidObj.address}/${pidObj.id}`);
        targetPID = new PID(pidObj.address, pidObj.id);
      } else {
        console.error(`[REMOTE] Invalid targetPID format:`, message.targetPID);
        return;
      }
      
      // 设置 targetPID 的系统引用
      targetPID.system = this.system;
      
      // 获取进程注册表
      const registry = ProcessRegistry.getInstance();
      console.log(`[REMOTE] Looking up target process in registry: ${targetPID.toString()}`);
      
      // 打印所有已注册的进程
      if (registry.getAllProcesses) {
        const allProcesses = registry.getAllProcesses();
        console.log(`[REMOTE] All registered processes:`, allProcesses);
      }
      
      // 尝试获取目标进程
      const targetProcess = registry.get(targetPID);
      
      if (targetProcess) {
        console.log(`[REMOTE] Found target process, sending message to: ${targetPID.toString()}`);
        
        // 准备消息 - 如果有发送者，确保它也是完整的PID对象
        let finalMessage = message.message;
        
        // 如果消息中包含 sender 字段，需要转换为 PID
        if (message.senderPID) {
          console.log(`[REMOTE] Message has sender: ${message.senderPID.toString()}`);
          let senderPID: PID;
          
          if (message.senderPID instanceof PID) {
            senderPID = message.senderPID;
          } else {
            const senderObj = message.senderPID as any;
            console.log(`[REMOTE] Converting sender PID object: ${senderObj.address}/${senderObj.id}`);
            senderPID = new PID(senderObj.address, senderObj.id);
          }
          
          // 设置系统引用
          senderPID.system = this.system;
          
          // 包装消息为带发送者的信封
          finalMessage = {
            sender: senderPID,
            message: message.message
          };
          
          console.log(`[REMOTE] Prepared message envelope with sender: ${senderPID.toString()}`);
        }
        
        // 发送消息给目标进程
        console.log(`[REMOTE] Sending user message to target process`);
        targetProcess.sendUserMessage(targetPID, finalMessage);
        console.log(`[REMOTE] Message delivered to target process`);
        
      } else {
        console.warn(`[REMOTE] Target process not found: ${targetPID.toString()}`);
        
        // 如果找不到目标，尝试在父地址空间中查找
        if (targetPID.address !== this.system.processRegistry.address()) {
          console.log(`[REMOTE] Target address differs from system registry address`);
          console.log(`[REMOTE] System registry address: ${this.system.processRegistry.address()}`);
          
          // 创建一个本地 PID 参考
          const localPID = new PID(this.system.processRegistry.address(), targetPID.id);
          console.log(`[REMOTE] Created local PID reference: ${localPID.toString()}`);
          
          // 查找本地进程
          const localProcess = registry.get(localPID);
          
          if (localProcess) {
            console.log(`[REMOTE] Found local process for: ${localPID.toString()}`);
            
            // 准备消息，与上面相同
            let finalMessage = message.message;
            
            if (message.senderPID) {
              console.log(`[REMOTE] Message has sender: ${message.senderPID.toString()}`);
              let senderPID: PID;
              
              if (message.senderPID instanceof PID) {
                senderPID = message.senderPID;
              } else {
                const senderObj = message.senderPID as any;
                console.log(`[REMOTE] Converting sender PID object: ${senderObj.address}/${senderObj.id}`);
                senderPID = new PID(senderObj.address, senderObj.id);
              }
              
              senderPID.system = this.system;
              
              finalMessage = {
                sender: senderPID,
                message: message.message
              };
              
              console.log(`[REMOTE] Prepared message envelope with sender for local delivery`);
            }
            
            // 发送消息给本地进程
            console.log(`[REMOTE] Sending user message to local process`);
            localProcess.sendUserMessage(localPID, finalMessage);
            console.log(`[REMOTE] Message delivered to local process`);
            
          } else {
            console.warn(`[REMOTE] Local process not found: ${localPID.toString()}`);
            
            // 最后尝试通过根 Actor 发送
            console.log(`[REMOTE] Attempting to route through root actor`);
            this.system.root.send(targetPID, message.message);
            
            // 检查是否有发送者，如果有则发送 DeadLetter 通知
            if (message.senderPID) {
              console.log(`[REMOTE] Sending DeadLetter notification to sender: ${message.senderPID.toString()}`);
              
              // 构造 DeadLetter 事件
              const deadLetter = {
                pid: targetPID,
                message: message.message,
                sender: message.senderPID
              };
              
              // 发布 DeadLetter 事件
              this.system.eventStream.publish({
                type: 'DeadLetter',
                ...deadLetter
              });
              
              // 如果是 Request 类型的消息，向发送者回复错误
              if (message.type === RemoteMessageType.Request) {
                console.log(`[REMOTE] Sending ErrorResponse for Request message`);
                
                // 构造错误响应
                const errorResponse: RemoteErrorResponse = {
                  type: RemoteMessageType.ErrorResponse,
                  error: `Target not found: ${targetPID.toString()}`,
                  messageId: message.messageId || 'unknown'
                };
                
                // 发送错误响应
                try {
                  await this.endpointManager.sendMessage(message.senderPID.address, errorResponse);
                  console.log(`[REMOTE] Error response sent to sender`);
                } catch (error) {
                  console.error(`[REMOTE] Failed to send error response:`, error);
                }
              }
            }
          }
        }
      }
    } catch (error) {
      console.error(`[REMOTE] Error handling normal message:`, error);
      
      // 如果是请求消息，发送错误响应
      if (message.type === RemoteMessageType.Request && message.senderPID && message.messageId) {
        const errorResponse: RemoteErrorResponse = {
          type: RemoteMessageType.ErrorResponse,
          error: error instanceof Error ? error.message : 'Unknown error',
          messageId: message.messageId
        };
        
        try {
          await this.endpointManager.sendMessage(message.senderPID.address, errorResponse);
        } catch (sendError) {
          console.error(`[REMOTE] Failed to send error response:`, sendError);
        }
      }
    }
  }

  // 处理发送给 Future 的响应
  private async handleResponseToFuture(message: RemoteMessage): Promise<void> {
    try {
      if (!message.targetPID) {
        console.warn('[REMOTE] Response message has no target PID');
        return;
      }
      
      const futurePid = message.targetPID;
      console.log(`[REMOTE] Handling response to future: ${futurePid.toString()}`);
      
      // 查找本地 Future 进程
      const futureProcess = this.system.processRegistry.get(futurePid);
      if (futureProcess) {
        console.log(`[REMOTE] Found future process, delivering response`);
        futureProcess.sendUserMessage(futurePid, message.message);
      } else {
        console.warn(`[REMOTE] Future process not found: ${futurePid.toString()}`);
        this.system.eventStream.publish(new Events.DeadLetter(
          futurePid,
          message.message,
          message.senderPID
        ));
      }
    } catch (error) {
      console.error('[REMOTE] Error handling response to future:', error);
    }
  }

  // 处理响应消息
  private async handleResponseMessage(message: RemoteMessage): Promise<void> {
    try {
      if (!message.targetPID) {
        console.warn('[REMOTE] 响应消息没有目标PID');
        return;
      }
      
      console.log(`[REMOTE] 处理响应消息到: ${message.targetPID.toString()}`);
      
      // 如果目标是local地址的future进程，则转为对本地Future对象的响应
      if (message.targetPID.address === 'local' && message.targetPID.id.startsWith('future$')) {
        console.log(`[REMOTE] 响应目标是本地Future: ${message.targetPID.toString()}`);
        const futureProcess = this.system.processRegistry.get(message.targetPID);
        
        if (futureProcess) {
          // 获取实际的响应内容，而不是整个RemoteMessage对象
          const actualResponse = message.message;
          
          // 如果消息包含messageData元数据，则创建更丰富的响应
          if (typeof message === 'object' && 'messageData' in message && message.messageData) {
            console.log(`[REMOTE] 发送带元数据的响应`);
            futureProcess.sendUserMessage(message.targetPID, message.messageData);
          } else {
            console.log(`[REMOTE] 找到Future进程，发送响应消息: ${typeof actualResponse}, 内容: ${actualResponse}`);
            // 直接发送消息内容，而不是整个Response对象
            futureProcess.sendUserMessage(message.targetPID, actualResponse);
          }
        } else {
          console.warn(`[REMOTE] 未找到Future进程: ${message.targetPID.toString()}`);
          this.system.eventStream.publish(new Events.DeadLetter(
            message.targetPID,
            message.message,
            message.senderPID
          ));
        }
      } else {
        console.log(`[REMOTE] 响应目标不是本地Future，尝试常规路由`);
        await this.handleNormalMessage(message);
      }
    } catch (error) {
      console.error('[REMOTE] 处理响应消息时出错:', error);
    }
  }

  /**
   * 创建远程服务器进程
   * @param remoteId 远程服务ID
   */
  private createServerProcess(remoteId: string): Process {
    console.log(`[REMOTE] Creating server process: ${remoteId}`);
    
    return {
      sendUserMessage: async (pid: PID, message: any): Promise<void> => {
        console.log(`[REMOTE] Server process received user message for ${pid.toString()}`);
        await this.handleRemoteMessage({
          type: RemoteMessageType.Normal,
          targetPID: pid,
          message
        });
      },
      
      sendSystemMessage: async (pid: PID, message: any): Promise<void> => {
        console.log(`[REMOTE] Server process received system message for ${pid.toString()}`);
        await this.handleRemoteMessage({
          type: RemoteMessageType.System,
          targetPID: pid,
          message
        });
      },
      
      stop: (pid: PID): void => {
        console.log(`[REMOTE] Stopping server process: ${pid.toString()}`);
      }
    };
  }

  /**
   * 处理远程终止消息
   * @param message 远程终止消息
   */
  private handleRemoteTerminate(message: RemoteTerminate): void {
    console.log(`[REMOTE] 处理远程终止消息`);
    const processRegistry = ProcessRegistry.getInstance();
    
    if (message.watcher && message.targetPID) {
      console.log(`[REMOTE] 创建本地PID: ${processRegistry.address()}/${message.targetPID.id}`);
      const localPid = new PID(processRegistry.address(), message.targetPID.id);
      
      // 转换为RemoteMessage格式
      const remoteMessage: RemoteMessage = {
        type: RemoteMessageType.System,
        targetPID: localPid,
        senderPID: message.watcher,
        message: {
          type: 'Terminate',
          targetPID: localPid,
          watcher: message.watcher
        }
      };
      
      // 处理转换后的消息
      this.handleRemoteMessage(remoteMessage);
    }
  }

  /**
   * 处理远程监视消息
   * @param message 远程监视消息
   */
  private handleRemoteWatch(message: RemoteWatch): void {
    console.log(`[REMOTE] 处理远程监视消息`);
    
    const processRegistry = ProcessRegistry.getInstance();
    
    if (message.watcher && message.targetPID) {
      console.log(`[REMOTE] 创建本地PID: ${processRegistry.address()}/${message.targetPID.id}`);
      const localPid = new PID(processRegistry.address(), message.targetPID.id);
      
      // 转换为RemoteMessage格式
      const remoteMessage: RemoteMessage = {
        type: RemoteMessageType.System,
        targetPID: localPid,
        senderPID: message.watcher,
        message: {
          type: 'Watch',
          targetPID: localPid,
          watcher: message.watcher
        }
      };
      
      // 处理转换后的消息
      this.handleRemoteMessage(remoteMessage);
    }
  }

  /**
   * 处理远程取消监视消息
   * @param message 远程取消监视消息
   */
  private handleRemoteUnwatch(message: RemoteUnwatch): void {
    console.log(`[REMOTE] 处理远程取消监视消息`);
    
    const processRegistry = ProcessRegistry.getInstance();
    
    if (message.watcher && message.targetPID) {
      console.log(`[REMOTE] 创建本地PID: ${processRegistry.address()}/${message.targetPID.id}`);
      const localPid = new PID(processRegistry.address(), message.targetPID.id);
      
      // 转换为RemoteMessage格式
      const remoteMessage: RemoteMessage = {
        type: RemoteMessageType.System,
        targetPID: localPid,
        senderPID: message.watcher,
        message: {
          type: 'Unwatch',
          targetPID: localPid,
          watcher: message.watcher
        }
      };
      
      // 处理转换后的消息
      this.handleRemoteMessage(remoteMessage);
    }
  }

  /**
   * 处理远程传递消息
   * @param message 远程传递消息
   */
  private handleRemoteDeliver(message: RemoteDeliver): void {
    console.log(`[REMOTE] 处理远程传递消息`);
    
    const processRegistry = ProcessRegistry.getInstance();
    
    if (message.targetPID) {
      console.log(`[REMOTE] 创建本地PID: ${processRegistry.address()}/${message.targetPID.id}`);
      const localPid = new PID(processRegistry.address(), message.targetPID.id);
      
      // 转换为RemoteMessage格式
      const remoteMessage: RemoteMessage = {
        type: RemoteMessageType.Normal, // 默认为普通消息
        targetPID: localPid,
        message: message.payload // 使用payload属性
      };
      
      // 处理转换后的消息
      this.handleRemoteMessage(remoteMessage);
    }
  }

  /**
   * 处理远程Future消息
   * @param message 远程Future消息
   */
  private handleRemoteFuture(message: RemoteFuture): void {
    console.log(`[REMOTE] 处理远程Future消息`);
    
    const processRegistry = ProcessRegistry.getInstance();
    
    if (message.targetPID) {
      console.log(`[REMOTE] 创建本地PID: ${processRegistry.address()}/${message.targetPID.id}`);
      const localPid = new PID(processRegistry.address(), message.targetPID.id);
      
      // 生成消息ID
      const messageId = `${Date.now()}-${Math.floor(Math.random() * 1000000)}`;
      
      // 转换为RemoteMessage格式
      const remoteMessage: RemoteMessage = {
        type: RemoteMessageType.Request,
        targetPID: localPid,
        message: message.payload, // 使用payload属性
        messageId: messageId
      };
      
      // 处理转换后的消息
      this.handleRemoteMessage(remoteMessage);
    }
  }
} 